import { Loading } from '@/global';
import { h, onMounted, reactive, VNode, UnwrapNestedRefs, ref } from 'vue';
import { ApiCode, ApiResult, Page } from '@/config/api_config/api_interface';

interface BusinessListGetMethodConfig<Params, Result>{
  params?: Params;
  usePagination?: boolean;
  immediateMounted?: boolean;
  apiMethod: (params: any) => Promise<ApiResult<Result[] | null>>,
}

/**
 * 通过表格响应对象以及方法
 * @param config 配置属性
 */
export function commonTableListReactive<Params, Result extends Object> (config: BusinessListGetMethodConfig<Params, Result>) {
  const dataList = reactive<Result[]>([]); // 数据列表
  const tableLoading = reactive<Loading>({ status: false }); // 表格loading对象
  const page = reactive<Page>({ pageIndex: 1, pageLimit: 10 }); // 分页对象
  const searchLoading = reactive<Loading>({ status: false }); // 查询按钮的loading对象

  // 执行初始化参数方法
  if (config.immediateMounted === undefined) config.immediateMounted = true;
  if (config.usePagination === undefined) config.usePagination = true;

  // 加载方法
  const onLoad = () => {
    if (!tableLoading.status) {
      tableLoading.status = true;
      dataList.splice(0, dataList.length);
      const params = config.usePagination ? { ...page, ...config.params } : config.params;
      config.apiMethod(params).then(res => {
        tableLoading.status = false;
        if (res.apiCode === ApiCode.Success) {
          if (res.result) {
            for (const item of res.result) {
              (dataList as Result[]).push(item as Result);
            }
            page.total = res.page?.total;
          }
        }
      }).catch(() => {
        tableLoading.status = false;
        searchLoading.status = false;
      });
    }
  };

  // 初始化挂载方法
  if (config.immediateMounted) {
    onMounted(() => {
      onLoad();
    });
  }

  // 刷新页面方法
  const onRefresh = () => {
    if (!searchLoading.status) {
      searchLoading.status = true;
      page.pageIndex = 1;
      onLoad();
    }
  };
  return {
    tableLoading, onLoad, page, onRefresh, dataList
  };
}
